//
//  MenuListView.m
//  MKUITestApp
//
//  Created by 苏尚进 on 2020/8/24.
//  Copyright © 2020 moon. All rights reserved.
//

#import "MenuListView.h"
#import "MenuView.h"
@interface MenuListView()
@property(nonatomic,strong) NSMutableArray<MenuView *> *viewCache;
@property(nonatomic,strong) UIView *contentView;
@property(nonatomic,strong) MKUIFlowLayoutConstraint *flowlayout;
@end

@implementation MenuListView
- (id)initWithFrame:(CGRect)frame{
    if (self=[super initWithFrame:frame]) {
        self.viewCache = [[NSMutableArray alloc] init];
        self.contentView = [[UIView alloc] init];
        [self addSubview:self.contentView];
        self.flowlayout = [[MKUIFlowLayoutConstraint alloc] initWithItems:@[] constraintParam:(MKUIFlowLayoutConstraintParam_V_T_L) contentInsets:UIEdgeInsetsMake(5, 40, 5, 20) interitemSpacing:5];
    }
    return self;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    CGRect bounds = self.bounds;
    self.contentView.frame = bounds;
    {
        CGRect bounds = self.contentView.bounds;
        self.flowlayout.bounds = bounds;
        [self.flowlayout layoutItemsWithResizeItems:YES];
    }
}
- (CGSize)sizeThatFits:(CGSize)size{
    return [self.flowlayout sizeThatFits:CGSizeMake(size.width, 99999999) resizeItems:YES];
}
- (NSArray<MenuView *> *)menuViews{
    return (NSArray<MenuView *> *)self.flowlayout.items;
}
- (void)setMenuList:(NSArray<Menu *> *)menuList{
    _menuList = menuList;
    [self __reloadData];
}
- (void)__reloadData{
    for (MenuView *v in [self menuViews]) {
        [v removeFromSuperview];
        v.menu = nil;
        [self.viewCache addObject:v];
    }
    NSMutableArray<MenuView *> *items = [[NSMutableArray alloc] initWithCapacity:self.menuList.count];
    for (Menu *menu in self.menuList) {
        MenuView *v = [self.viewCache lastObject];
        [self.viewCache removeLastObject];
        if(!v){
            v = [[MenuView alloc] init];
        }
        v.menu = menu;
        [self addSubview:v];
        [items addObject:v];
    }
    self.flowlayout.items = items;
    [self setNeedsLayout];
}
@end
